#pragma once
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include "Log.hpp"
#include <errno.h>
#include <cstring>
#include "Comm.hpp"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include "nocopy.hpp"

static const std::string default_ip = "0.0.0.0";
static const uint16_t default_port = 8888;

class UdpServer: public nocopy
{
public:
    UdpServer(const std::string& ip = default_ip, uint16_t port = default_port)
    :_ip(ip), _port(port), _sockfd(-1)
    {}
    void Init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            lg.LogMessage(Error, "errno: %d error: %s\n", errno, strerror(errno));
            exit(Socket_Error);
        }
        
        lg.LogMessage(Info, "socket success, sockfd: %d\n", _sockfd);

        struct sockaddr_in local;   //#include <netinet/in.h>
        bzero(&local, sizeof local); //#include <strings.h>
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str()); //#include <arpa/inet.h>
        int n = bind(_sockfd, (sockaddr*)&local, sizeof local);
        if(n < 0)
        {
            lg.LogMessage(Error, "errno: %d error: %s\n", errno, strerror(errno));
            exit(Bind_Error);
        }
    }
    void Start()
    {
        char buffer[1024];
        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof peer;
            int n = recvfrom(_sockfd, buffer, sizeof buffer - 1, 0, (sockaddr*)&peer, &len);
            if(n > 0)
            {
                buffer[n] = 0; //低级网络函数不会填充0
                sendto(_sockfd, buffer, strlen(buffer), 0, (sockaddr*)&peer, len);
            }
        }
    }
    ~UdpServer()
    {}
private:
    std::string _ip;
    uint16_t _port;
    int _sockfd;
};